#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define LISTEN_SZ 10

int main(int argc, char const *argv[])
{
    struct sockaddr_in server_addr, client_addr;

    bzero(&server_addr, sizeof(server_addr));

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(atoi(argv[2]));
    server_addr.sin_addr.s_addr = inet_addr(argv[1]);

    int sfd, cfd;
    ssize_t sbytes, rbytes;
    char buffer[1024] = {0};

    sfd = socket(AF_INET, SOCK_STREAM, 0);

    // 绑定监听 连接
    int ret = bind(sfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (ret == -1) {
        perror("bind error");
        exit(EXIT_FAILURE);
    }

    ret = listen(sfd, LISTEN_SZ);
    if (ret == -1) {
        perror("listen error");
        exit(EXIT_FAILURE);
    }

    socklen_t len = sizeof(struct sockaddr_in);
    bzero(&client_addr, len);
    cfd = accept(sfd, (struct sockaddr *)&client_addr, &len);
    if (cfd == -1) {
        perror("accept error");
        exit(EXIT_FAILURE);
    }
    printf("client ip: %s, port: %d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

    for(;;) {
        memset(buffer, 0, sizeof(buffer));
        // 接收客户端消息
        rbytes = recv(cfd, buffer, sizeof(buffer), 0);
        if (rbytes == -1) {
            perror("recv error");
            exit(EXIT_FAILURE);
        } else if (rbytes == 0) {
            printf("client is offine\n");
            exit(EXIT_FAILURE); 
        } else if (rbytes > 0) {
            printf("recv msg: %s\n", buffer);
        }

        sleep(1);
    }
    
    close(sfd);
    close(cfd);
    return 0;
}
